package com.maltys.dynamicdatasource.common.context;

import com.maltys.dynamicdatasource.common.enums.DataSourceEnum;
import org.springframework.util.StringUtils;

public class DynamicDataSourceContext {
    private static final ThreadLocal<String> DATASOURCE_CONTEXT_KEY_HOLDER = new ThreadLocal<>();

    /**
     * 设置源的标志
     *
     * @param key
     */
    public static void setContextKey(String key) {
        DATASOURCE_CONTEXT_KEY_HOLDER.set(key);
    }

    /**
     * 多线程持有当前线程的数据源key
     */
    public static String getContextKey() {
        String key = DATASOURCE_CONTEXT_KEY_HOLDER.get();
        return StringUtils.isEmpty(key) ? DataSourceEnum.PRIME.getKey() : key;
    }

    /**
     * 线程退出 移除当前数据库key
     */
    public static void removeContextKey() {
        DATASOURCE_CONTEXT_KEY_HOLDER.remove();
    }
}
